import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView
} from 'react-native'
import { connect } from 'react-redux'

import { theme_app, theme_text } from '../../utils/appTheme'
import HeaderDefault from '../../components/header/HeaderDefault'
import { getAdviseVoByQrNo, submitCheckTask } from '../../netServer/dispense'
import Toast from 'react-native-simple-toast'
import { isNotEmptyArray } from '../../utils/structureJudgment'
import { Empty } from '../../components/Empty/Empty'

class DispenseReviewResult extends Component {
  constructor(props) {
    super(props)
    this.state = {
      enableSubmmit: false,
      scanStatus: false,
      patient: {},
      advList: [],
      taskList: []
    }
  }

  static navigationOptions = ({ navigation }) => ({
    gesturesEnabled: false,
    header: (
      <HeaderDefault
        title="配药复核确认"
        backBtnOnPress={() => {
          // navigation.navigate('Home')
          navigation.goBack(navigation.state.params.currentRouterKey)
        }}
        // rihghtBtnOnPress={() => {
        //   navigation.state.params.clickRightMethod()
        // }}
        // rightImg={require('./src/add.png')}
        // flag={true}
      />
    )
  })

  componentDidMount() {
    this._loadData()
  }

  _loadData() {
    let params = new FormData()
    params.append('adviseNo', this.props.navigation.state.params.adviseNo)
    params.append('type', 'check')

    getAdviseVoByQrNo(params, resp => {
      let { code, msg, data } = resp

      if (code == '0') {
        let { patient, advList, taskList = [] } = data
        let isEnable = false
        if (isNotEmptyArray(taskList)) {
          let itemf = taskList[0]
          if (itemf.status === '待执行') {
            isEnable = true
          }
        }

        this.setState({
          patient: patient,
          advList: advList,
          taskList: taskList,
          scanStatus: true,
          enableSubmmit: isEnable
        })
      } else {
        this.setState({
          scanStatus: false
        })
      }
    })
  }

  _submitCheckTask = () => {
    let params = new FormData()
    let { user_id } = this.props.user_info

    // let mainId = null

    // for (let i = 0; i < this.state.taskList.length; i++) {
    //   let element = this.state.taskList[i]
    //   if (i === 0) {
    //     mainId = element.main_task_id
    //   }

    //   params.append('taskIds[' + i + ']', element.task_id)
    // }

    let element = this.state.taskList[0]

    params.append('userId', user_id)
    params.append('mainTaskId', element.main_task_id)
    params.append('taskIds[' + 0 + ']', element.task_id)

    submitCheckTask(params, resp => {
      let { code, msg, data } = resp

      if (code == '0') {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
        let {
          successGoBack,
          currentRouterKey
        } = this.props.navigation.state.params

        successGoBack ? successGoBack() : null
        this.props.navigation.goBack(currentRouterKey)
      } else {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
      }
    })
  }

  render() {
    if (!this.state.scanStatus) {
      return <Empty titleStr="未获取到二维码信息" />
    }

    let {
      name,
      bed_no,
      sex,
      age,
      diagnose,
      grade_name,
      allergy
    } = this.state.patient
    return (
      <View style={styles.container}>
        <View style={{ flex: 1 }}>
          <View
            style={{
              width: screenWidth,
              height: 100,
              flexDirection: 'row',
              backgroundColor: 'white',
              borderBottomWidth: 1,
              borderBottomColor: '#efefef'
            }}
          >
            <View style={{ width: 100, height: 100, padding: 10 }}>
              <Image
                resizeMode="stretch"
                source={require('./src/2e515611327925ef332b71e7d1377678.jpg')}
                style={{ width: 80, height: 80 }}
              />
            </View>

            <View style={{ flex: 1, flexDirection: 'row' }}>
              <View
                style={{
                  flex: 1,
                  paddingLeft: 5,
                  paddingTop: 12,
                  paddingBottom: 12
                }}
              >
                <View style={{ flex: 1 }}>
                  <Text style={{ fontSize: 15 }}>{name}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text>
                    {sexIndexToSexString(sex)}
                    {sex ? '/' : ''}
                    {age}
                  </Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={{ color: 'green' }}>{grade_name}</Text>
                </View>
              </View>

              <View
                style={{
                  flex: 1,
                  paddingLeft: 5,
                  paddingTop: 12,
                  paddingBottom: 12
                }}
              >
                <View style={{ flex: 1 }}>
                  <Text style={{ fontSize: 15 }}>{bed_no}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text>{diagnose}</Text>
                </View>
                <View style={{ flex: 1 }}>
                  <Text style={{ color: 'red' }}>{allergy}</Text>
                </View>
              </View>
            </View>
          </View>
          <ScrollView style={{ flex: 1, backgroundColor: 'white' }}>
            {this.state.advList.map((value, index) => {
              return (
                <View
                  key={index}
                  style={{
                    width: screenWidth,
                    padding: 10,
                    flexDirection: 'row',
                    borderBottomWidth: 1,
                    borderBottomColor: '#efefef'
                  }}
                >
                  <View style={{ width: 0.5 * screenWidth }}>
                    <Text>{value.medName}</Text>
                    <Text>
                      {value.standard}/{value.use_unit}&nbsp;&nbsp;&nbsp;&nbsp;
                      {value.measure}
                    </Text>
                  </View>
                  <View style={{ width: 0.5 * screenWidth }}>
                    <Text>
                      &nbsp;&nbsp;&nbsp;&nbsp;{value.usageName}
                      &nbsp;&nbsp;&nbsp;&nbsp;{value.freqCode}
                    </Text>
                    <Text style={{ color: 'red' }}>
                      执行时间：{value.execute_time}
                    </Text>
                  </View>
                </View>
              )
            })}
          </ScrollView>

          {/* 分割线 */}
          <View
            style={{
              borderColor: '#000',
              height: 0,
              borderWidth: 1,
              borderStyle: 'dotted'
            }}
          />
        </View>

        <View
          style={{
            width: screenWidth,
            height: 45,
            lineHeight: 45,
            backgroundColor: '#444',
            color: 'white',
            fontSize: 20,
            flexDirection: 'row'
          }}
        >
          <TouchableOpacity
            onPress={this._submitCheckTask}
            disabled={!this.state.enableSubmmit}
            style={{
              flex: 1,
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: this.state.enableSubmmit ? 'green' : 'gray'
            }}
          >
            <Text style={{ color: 'white', fontSize: 16 }}>确定</Text>
          </TouchableOpacity>
        </View>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme_app.bg_color
  }
})

function select(store) {
  return {
    user_info: store.userInfo.user_info
  }
}

export default connect(select)(DispenseReviewResult)
